<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div>
            <el-button
              v-permission="'users.delete'"
              type="danger"
              :disabled="selectedIds.length === 0"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button
              v-permission="'users.update'"
              type="warning"
              :disabled="selectedIds.length === 0"
              @click="handleBatchUpdateStatus(0)"
            >
              批量禁用
            </el-button>
            <el-button
              v-permission="'users.update'"
              type="success"
              :disabled="selectedIds.length === 0"
              @click="handleBatchUpdateStatus(1)"
            >
              批量启用
            </el-button>
            <el-button
              v-permission="'users.create'"
              type="primary"
              @click="handleAdd"
            >
              新增用户
            </el-button>
            <el-button
              v-permission="'users.export'"
              @click="handleExport"
            >
              导出
            </el-button>
            <el-button
              v-permission="'users.create'"
              @click="handleImport"
            >
              导入
            </el-button>
          </div>
        </div>
      </template>
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="queryForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="queryForm.dept_id" placeholder="请选择部门" clearable filterable>
            <el-option
              v-for="dept in departmentOptions"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="max_devices" label="最大设备数" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="info">{{ row.max_devices || 1 }}台</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="在线状态" width="100" align="center">
          <template #default="{ row }">
            <el-tooltip :content="row.is_online ? '在线' : '离线'" placement="top">
              <div 
                :style="{ 
                  width: '12px', 
                  height: '12px', 
                  borderRadius: '50%', 
                  backgroundColor: row.is_online ? '#67C23A' : '#909399',
                  display: 'inline-block',
                  cursor: 'pointer'
                }"
                class="online-status-icon"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="department.name" label="部门" />
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button
              v-permission="'users.update'"
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-permission="'users.view'"
              type="info"
              link
              @click="handleViewPermissions(row)"
            >
              权限
            </el-button>
            <el-button
              v-permission="'users.delete'"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-button
              v-permission="'users.assign'"
              type="warning"
              link
              @click="handleForceLogout(row)"
            >
              强制登出
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
    
    <UserDialog
      v-model="dialogVisible"
      :user-id="currentUserId"
      @success="handleSuccess"
    />

    <!-- 用户权限对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="用户权限" width="800px">
      <el-tabs v-model="permissionActiveTab" v-if="currentUserPermissions">
        <el-tab-pane label="所有权限" name="all">
          <el-table :data="currentUserPermissions.permissions || []" border max-height="400">
            <el-table-column prop="name" label="权限名称" />
            <el-table-column prop="code" label="权限编码" />
            <el-table-column prop="type_name" label="类型" width="100" />
            <el-table-column prop="resource" label="资源" width="120" />
            <el-table-column prop="action_name" label="操作" width="100" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="菜单权限" name="menus">
          <el-table :data="currentUserPermissions.menu_permissions || []" border max-height="400">
            <el-table-column prop="name" label="权限名称" />
            <el-table-column prop="code" label="权限编码" />
            <el-table-column prop="menu.title" label="所属菜单" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="按钮权限" name="buttons">
          <el-table :data="currentUserPermissions.button_permissions || []" border max-height="400">
            <el-table-column prop="name" label="权限名称" />
            <el-table-column prop="code" label="权限编码" />
            <el-table-column prop="resource" label="资源" width="120" />
            <el-table-column prop="action_name" label="操作" width="100" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入用户" width="500px">
      <el-upload
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="importFile ? [{ name: importFile.name }] : []"
        accept=".xlsx,.xls"
        drag
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传xlsx/xls文件，且不超过10MB。Excel格式：ID、用户名、昵称、邮箱、手机、状态、部门、角色、创建时间
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="importLoading" @click="handleImportSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import request from '@/utils/request'
import UserDialog from './components/UserDialog.vue'

const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const currentUserId = ref(null)
const selectedIds = ref([])
const departmentOptions = ref([])
const permissionDialogVisible = ref(false)
const permissionActiveTab = ref('all')
const currentUserPermissions = ref(null)

const queryForm = reactive({
  username: '',
  dept_id: null,
  status: null,
})

const pagination = reactive({
  page: 1,
  pageSize: 15,
  total: 0,
})

const fetchData = async () => {
  loading.value = true
  try {
    const response = await request.get('/users', {
      params: {
        ...queryForm,
        page: pagination.page,
        page_size: pagination.pageSize,
      },
    })
    if (response.code === 200) {
      tableData.value = response.data.data
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  pagination.page = 1
  fetchData()
}

const handleReset = () => {
  Object.assign(queryForm, {
    username: '',
    dept_id: null,
    status: null,
  })
  handleQuery()
}

const handleAdd = () => {
  currentUserId.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  currentUserId.value = row.id
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const response = await request.delete(`/users/${row.id}`)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
    }
  }
}

const handleForceLogout = async (row) => {
  try {
    await ElMessageBox.confirm('确定要强制登出该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const response = await request.post(`/users/${row.id}/force-logout`)
    if (response.code === 200) {
      ElMessage.success('强制登出成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('强制登出失败:', error)
    }
  }
}

const handleSizeChange = () => {
  fetchData()
}

const handlePageChange = () => {
  fetchData()
}

const handleSuccess = () => {
  dialogVisible.value = false
  fetchData()
}

// 批量选择
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const response = await request.post('/users/batch-destroy', {
      ids: selectedIds.value,
    })
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量删除失败')
    }
  }
}

// 批量更新状态
const handleBatchUpdateStatus = async (status) => {
  try {
    const statusText = status === 1 ? '启用' : '禁用'
    await ElMessageBox.confirm(`确定要${statusText}选中的 ${selectedIds.value.length} 个用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const response = await request.post('/users/batch-update-status', {
      ids: selectedIds.value,
      status,
    })
    if (response.code === 200) {
      ElMessage.success(`批量${statusText}成功`)
      selectedIds.value = []
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量更新失败')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    loading.value = true
    const response = await request.get('/users/export/list', {
      params: queryForm,
      responseType: 'blob',
    })
    // 创建下载链接
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `用户列表_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 导入
const importDialogVisible = ref(false)
const importFile = ref(null)
const importLoading = ref(false)

const handleImport = () => {
  importDialogVisible.value = true
}

const handleImportSubmit = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  const formData = new FormData()
  formData.append('file', importFile.value)

  importLoading.value = true
  try {
    const res = await request.post('/users/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
      if (res.code === 200) {
        const message = `导入完成，成功：${res.data.success_count}条，失败：${res.data.fail_count}条`
        if (res.data.errors && res.data.errors.length > 0) {
          ElMessage.warning(message + '，部分数据导入失败，请查看控制台')
          console.warn('导入错误详情：', res.data.errors)
        } else {
          ElMessage.success(message)
        }
        importDialogVisible.value = false
        importFile.value = null
        fetchData()
      }
  } catch (error) {
    ElMessage.error('导入失败')
  } finally {
    importLoading.value = false
  }
}

const handleFileChange = (file) => {
  importFile.value = file.raw
}

// 查看用户权限
const handleViewPermissions = async (row) => {
  try {
    const response = await request.get(`/users/${row.id}/permissions`)
    if (response.code === 200) {
      currentUserPermissions.value = response.data
      permissionDialogVisible.value = true
      permissionActiveTab.value = 'all'
    }
  } catch (error) {
    ElMessage.error('获取用户权限失败')
  }
}

// 加载部门选项
const loadDepartments = async () => {
  try {
    const response = await request.get('/departments', {
      params: { tree: true, status: 1 },
    })
    if (response.code === 200) {
      // 扁平化部门树
      const flattenDepts = (depts) => {
        let result = []
        depts.forEach(dept => {
          result.push({ id: dept.id, name: dept.name })
          if (dept.children && dept.children.length > 0) {
            result = result.concat(flattenDepts(dept.children))
          }
        })
        return result
      }
      departmentOptions.value = flattenDepts(response.data)
    }
  } catch (error) {
    console.error('加载部门列表失败:', error)
  }
}

onMounted(() => {
  fetchData()
  loadDepartments()
})
</script>

<style scoped lang="scss">
.user-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .online-status-icon {
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      transform: scale(1.2);
    }
  }
}
</style>

